package com.sunday.pinxinghui.model.mine;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.Constants;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.common.widgets.ptr.PtrClassicFrameLayout;
import com.sunday.common.widgets.ptr.PtrDefaultHandler;
import com.sunday.common.widgets.ptr.PtrFrameLayout;
import com.sunday.common.widgets.ptr.PtrHandler;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.pinxinghui.R;
import com.sunday.pinxinghui.adapter.CommonAdapter;
import com.sunday.pinxinghui.adapter.ViewHolder;
import com.sunday.pinxinghui.base.BaseApplication;
import com.sunday.pinxinghui.entity.AmountDetail;
import com.sunday.pinxinghui.entity.Member;
import com.sunday.pinxinghui.network.ApiClient;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.sunday.pinxinghui.R.id.balance;


/**
 * Created by 刘涛 on 2017/8/11.
 */

public class MyIntegralActivity extends BaseActivity {


    @Bind(R.id.title_view)
    TextView titleView;
    @Bind(R.id.total_integral)
    TextView totalIntegral;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.right_btn)
    ImageView rightBtn;
    @Bind(R.id.txt1)
    TextView textView;
    @Bind(R.id.ptr_frame)
    PtrClassicFrameLayout ptrFrame;

    private long memberId;
    private CommonAdapter<AmountDetail> adapter;
    private List<AmountDetail> dataSet = new ArrayList<>();
    private int pageNo = 1, lastVisibleItem;
    private boolean isCanloadMore;
    private LinearLayoutManager layoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_integral);
        ButterKnife.bind(this);
        titleView.setText("我的积分");
        rightBtn.setVisibility(View.VISIBLE);
        rightBtn.setImageResource(R.mipmap.score_rule);
        memberId = BaseApplication.getInstance().getMember().getId();
        //memberId= Constants.TEST_MEMBERID;
        handlerRecyclerView();
        getMember();

    }

    private void handlerRecyclerView() {
        layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new CommonAdapter<AmountDetail>(mContext, R.layout.list_bill_item, dataSet) {
            @Override
            public void convert(ViewHolder holder, AmountDetail amountDetail, int position) {
                bindData(holder, amountDetail, position);
            }

        };
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext)
                .drawable(R.drawable.shape_divider)
                .build());
        recyclerView.setAdapter(adapter);
        ptrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                pageNo = 1;
                getMember();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, recyclerView, header);
            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == adapter.getItemCount() && isCanloadMore) {
                    getData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });

    }

    private void getMember() {
        Call<ResultDO<Member>> call = ApiClient.getApiAdapter().getMember(memberId);
        call.enqueue(new Callback<ResultDO<Member>>() {
            @Override
            public void onResponse(Call<ResultDO<Member>> call, Response<ResultDO<Member>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    Member member = response.body().getResult();
                    textView.setVisibility(member.getScore() == 0 ? View.GONE : View.VISIBLE);
                    // recyclerView.setVisibility(member.getScore() == 0 ? View.GONE : View.VISIBLE);
                    totalIntegral.setText(String.valueOf(member.getScore()));
                    getData();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<Member>> call, Throwable t) {

            }
        });
    }

    private void bindData(ViewHolder holder, AmountDetail amountDetail, int position) {
        ((TextView) holder.getView(R.id.time)).setText(amountDetail.getTime());
        ((TextView) holder.getView(R.id.title)).setText(amountDetail.getMemo());
        if (amountDetail.getAmount().compareTo(BigDecimal.ZERO) > -1) {
            ((TextView) holder.getView(R.id.money)).setTextColor(ContextCompat.getColor(mContext, R.color.main_color));
            ((TextView) holder.getView(R.id.money)).setText("+");
        } else {
            ((TextView) holder.getView(R.id.money)).setTextColor(ContextCompat.getColor(mContext, R.color._333));
            ((TextView) holder.getView(R.id.money)).setText("");
        }
        ((TextView) holder.getView(R.id.money)).append(
                String.format("%s", amountDetail.getAmount().setScale(2, RoundingMode.HALF_UP)));
    }


    private void getData() {
        showLoadingDialog(0);
        Call<ResultDO<List<AmountDetail>>> call = ApiClient.getApiAdapter().getAmountList(memberId, 2, pageNo, Constants.PAGE_SIZE);
        call.enqueue(new Callback<ResultDO<List<AmountDetail>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<AmountDetail>>> call, Response<ResultDO<List<AmountDetail>>> response) {
                if (isFinish) {
                    return;
                }
                dissMissDialog();
                // ptrFrame.refreshComplete();
                ResultDO<List<AmountDetail>> resultDO = response.body();
                if (resultDO == null) {
                    return;
                }

                if (resultDO.getCode() == 0) {
                    if (resultDO.getResult() == null || resultDO.getResult().size() == 0) {
                        return;
                    }
                    if (pageNo == 1) {
                        dataSet.clear();
                    }
                    dataSet.addAll(resultDO.getResult());
                    if (resultDO.getResult().size() == Constants.PAGE_SIZE) {
                        isCanloadMore = true;
                        pageNo++;
                    } else {
                        isCanloadMore = false;
                    }
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<AmountDetail>>> call, Throwable t) {
                // ptrFrame.refreshComplete();
                dissMissDialog();
            }
        });
    }

    @OnClick({R.id.right_btn})
    void onClick() {
        intent = new Intent(mContext, IntegralRuleActivity.class);
        startActivity(intent);
    }
}
